package com.icinfo.cloud.provider.punish.common.datareport.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.exception.DataReportException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SpringContextUtil;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseAdditionalDataReportDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportRecordQueryDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CaseDataReportStageInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CertTypeDataReportEnum;
import com.icinfo.cloud.provider.punish.common.datareport.enums.ReportDataTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.CaseDataReportRecordMapper;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.CaseDataReportStageInfoMapper;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportRecord;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportStageInfo;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseAdditionalDataReportService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportRecordService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportStageInfoService;
import com.icinfo.cloud.provider.punish.common.datareport.vo.CaseDataReportRecordVo;
import com.icinfo.cloud.provider.punish.common.datareport.vo.CaseDataReportStageInfoVo;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.SendWayEnum;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceEnum;
import com.icinfo.cloud.provider.punish.ucase.caseadditional.mapper.CaseAdditionalRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.caseadditional.model.CaseAdditionalRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartiesRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReasonMainRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseAdditionalTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseAppendixRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseReasonMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesDetailInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReasonMainRecordVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Desc 描述
 * @Author mahan
 * @Date 2022/12/19
 */
@Slf4j
@Service
public class CaseAdditionalDataReportServiceImpl implements ICaseAdditionalDataReportService {
	private static final String TERRITORY_CODE_PREFIX = "001";
	private static final String BASE_HTTP = "E5BeGhl3e4jPUbd8.htm";
	private static final String INFORM_HTTP = "Af5fA3wf55nzOf2e.htm";
	private static final String DECISION_HTTP = "2Yt9eL497ZdbM0bf.htm";
	private static final String EXECUTE_HTTP = "ydz5c15I5aVW4ru2.htm";
	private static final String CASE_CLOSED_HTTP = "U0odx61fHvb6Jc1f.htm";
	@Resource
	private CaseAdditionalRecordMapper caseAdditionalRecordMapper;
	@Resource
	private ISysDepartParamService sysDepartParamService;
	@Resource
	private ICasePartiesRecordService casePartiesRecordService;
	@Resource
	private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
	@Resource
	private ICaseReasonMainRecordService caseReasonMainRecordService;
	@Resource
	private ICaseDataReportRecordService caseDataReportRecordService;
	@Resource
	private ICaseDataReportStageInfoService caseDataReportStageInfoService;
	@Resource
	private CaseDataReportRecordMapper caseDataReportRecordMapper;
	@Resource
	private CaseAppendixRecordMapper caseAppendixRecordMapper;
	@Resource
	private CasePartiesRecordMapper casePartiesRecordMapper;
	@Resource
	private CaseDataReportStageInfoMapper caseDataReportStageInfoMapper;




	/**
	 * 查询所有需要的上报的数据，并逐个阶段上报
	 * @param
	 */
	@Override
	public String caseAdditionalDataReportByIds(CaseAdditionalDataReportDto dto){
		StringBuilder msg = new StringBuilder();
		List<String> ids = dto.getIdList();
		if(ids !=null && ids.size() > 0){
			for(String caseAdditionalId : ids){
				String reMsg = caseAdditionalDataReportForInterface(caseAdditionalId, dto.getStageIds(), dto.getUpdateCaseStatus());
				msg.append(reMsg);
			}
		}
		return msg.toString();
	}

	/**
	 * 上报补录表信息
	 * @param caseAdditionalId
	 */
	@Override
	public boolean caseAdditionalDataReport(String caseAdditionalId) {
		CaseAdditionalRecord caseAdditionalRecord = caseAdditionalRecordMapper.selectByPrimaryKey(caseAdditionalId);
		//判断是否允许数据上报
		this.judgeAllowDataReport(caseAdditionalRecord);

		//获取当事人信息(目前不考虑多当事人且分别处罚，所以当事人只取第一个)
		CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
		queryDto.setCaseId(caseAdditionalRecord.getId());
		queryDto.setIsQueryInvalidData(YesOrNoEnum.NO.getCode());
		List<CasePartiesInfoVo> partiesInfo = casePartiesRecordMapper.selectCasePartiesInfoListForAdditional(queryDto);
		CasePartiesInfoVo partInfoVO = partiesInfo.get(Constant.INTEGER_0);
		partInfoVO.setPartyId(null);

		//上报基础信息
		Result baseResult = this.reportBaseInfo(caseAdditionalRecord, partInfoVO);

		//上报处罚告知
		Result informResult = Result.success("");
		if (!CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
			informResult = this.reportInformInfo(caseAdditionalRecord, partInfoVO);
		}
		if(baseResult.getCode() == 200){
			//上报决定信息
			Result decisionResult = this.reportDecisionInfo(caseAdditionalRecord, partInfoVO);

			//如果没有结案，只上报到决定阶段
			if(YesOrNoEnum.NO.getCode().equals(caseAdditionalRecord.getCaseCloseStatus())){
				return baseResult.getCode() == 200 && informResult.getCode() == 200 && decisionResult.getCode() == 200;
			}

			//上报执行信息
			Result executeResult = this.reportExecuteInfo(caseAdditionalRecord, partInfoVO);

			//上报结案信息
			Result closeResult = this.reportCloseInfo(caseAdditionalRecord, partInfoVO);
			return baseResult.getCode() == 200 && informResult.getCode() == 200 && decisionResult.getCode() == 200 && executeResult.getCode() == 200 && closeResult.getCode() == 200;
		}
		return false;
	}


	/**
	 * 上报补录表信息（调接口使用）
	 * @param caseAdditionalId
	 */
	@Override
	public String caseAdditionalDataReportForInterface(String caseAdditionalId, List<String> stageIds, String updateCaseStatus) {
		CaseAdditionalRecord caseAdditionalRecord = caseAdditionalRecordMapper.selectByPrimaryKey(caseAdditionalId);
		if(caseAdditionalRecord == null){
			throw new BusinessException("补录案件不存在！");
		}
		//判断是否允许数据上报
		this.judgeAllowDataReport(caseAdditionalRecord);

		//获取当事人信息(目前不考虑多当事人且分别处罚，所以当事人只取第一个)
		CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
		queryDto.setCaseId(caseAdditionalRecord.getId());
		queryDto.setIsQueryInvalidData(YesOrNoEnum.NO.getCode());
		List<CasePartiesInfoVo> partiesInfo = casePartiesRecordMapper.selectCasePartiesInfoListForAdditional(queryDto);
		if(partiesInfo == null || partiesInfo.size() == 0){
			throw new BusinessException("当前案件缺少当事人信息！");
		}
		CasePartiesInfoVo partInfoVO = partiesInfo.get(Constant.INTEGER_0);
		partInfoVO.setPartyId(null);

		StringBuilder msg = new StringBuilder();

		if (stageIds.contains(ReportDataTypeEnum.BASE.getCode())) {
			//上报基础信息
			Result baseResult = this.reportBaseInfo(caseAdditionalRecord, partInfoVO);
			msg.append(baseResult.getMessage());
		}

		if (stageIds.contains(ReportDataTypeEnum.INFORM.getCode())) {
			//上报处罚告知
			if (!CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
				Result informResult = this.reportInformInfo(caseAdditionalRecord, partInfoVO);
				msg.append(informResult.getMessage());
			}
		}

		if (stageIds.contains(ReportDataTypeEnum.DECISION.getCode())) {
			//上报决定信息
			Result decisionResult = this.reportDecisionInfo(caseAdditionalRecord, partInfoVO);
			msg.append(decisionResult.getMessage());
		}

		if (stageIds.contains(ReportDataTypeEnum.EXECUTE.getCode())) {
			//上报执行信息
			Result executeResult = this.reportExecuteInfo(caseAdditionalRecord, partInfoVO);
			msg.append(executeResult.getMessage());
		}

		if (stageIds.contains(ReportDataTypeEnum.CASE_CLOSED.getCode())) {
			//上报结案信息
			Result closeResult = this.reportCloseInfo(caseAdditionalRecord, partInfoVO);
			msg.append(closeResult.getMessage());
		}
		//查询上报记录，如果已结案，并且已完成上报个数为5，（如果是决定，并且上报个数是3）则表示已经补录上报成功，需要更新状态
		if(YesOrNoEnum.YES.getCode().equals(updateCaseStatus)){
			Example caseAdditionalExample = new Example(CaseDataReportStageInfo.class);
			caseAdditionalExample.createCriteria().andEqualTo("caseId", caseAdditionalId)
					.andEqualTo("isFinishReport", YesOrNoEnum.YES.getCode());
			int count = caseDataReportStageInfoMapper.selectCountByExample(caseAdditionalExample);
			if(YesOrNoEnum.YES.getCode().equals(caseAdditionalRecord.getCaseCloseStatus()) && count == 5){
				CaseAdditionalRecord update = new CaseAdditionalRecord();
				update.setId(caseAdditionalId);
				update.setCaseAuditStatus(Constant.STRING_4);
				update.setCaseSuccessTime(LocalDateTime.now());
				caseAdditionalRecordMapper.updateByPrimaryKeySelective(update);
			}
			if(YesOrNoEnum.NO.getCode().equals(caseAdditionalRecord.getCaseCloseStatus()) && count == 3){
				CaseAdditionalRecord update = new CaseAdditionalRecord();
				update.setId(caseAdditionalId);
				update.setCaseAuditStatus(Constant.STRING_4);
				update.setCaseSuccessTime(LocalDateTime.now());
				caseAdditionalRecordMapper.updateByPrimaryKeySelective(update);
			}
		}
		return msg.toString();
	}

	/**
	 * 查询审批状态2和5的数据，全部上报
	 */
	@Override
	public void reportByCaseStatus(CaseAdditionalDataReportDto dto){
		Example caseAdditionalExample = new Example(CaseAdditionalRecord.class);
		caseAdditionalExample.createCriteria().andEqualTo("caseAuditStatus", dto.getCaseStatus());
		List<CaseAdditionalRecord> list = caseAdditionalRecordMapper.selectByExample(caseAdditionalExample);
		if(list != null && list.size() > 0){
			for(CaseAdditionalRecord caseAdditionalRecord : list){
				try {
					//判断是否允许数据上报
					boolean isAllow = this.judgeIsAllowDataReport(caseAdditionalRecord);
					if(isAllow){
						String caseAdditionalId = caseAdditionalRecord.getId();
						caseAdditionalDataReportByStatus(caseAdditionalId, dto.getStageIds(), dto.getUpdateCaseStatus());
					}
				}catch (Exception e){
					log.error("-------上报补录案件失败--------", e);
				}
			}
		}
	}

	/**
	 *
	 * @param caseAdditionalId
	 * @param stageIds
	 * @param updateCaseStatus
	 * @return
	 */
	private void caseAdditionalDataReportByStatus(String caseAdditionalId, List<String> stageIds, String updateCaseStatus) {
		CaseAdditionalRecord caseAdditionalRecord = caseAdditionalRecordMapper.selectByPrimaryKey(caseAdditionalId);
		if(caseAdditionalRecord == null){
			throw new BusinessException("补录案件不存在！");
		}

		//获取当事人信息(目前不考虑多当事人且分别处罚，所以当事人只取第一个)
		CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
		queryDto.setCaseId(caseAdditionalRecord.getId());
		queryDto.setIsQueryInvalidData(YesOrNoEnum.NO.getCode());
		List<CasePartiesInfoVo> partiesInfo = casePartiesRecordMapper.selectCasePartiesInfoListForAdditional(queryDto);
		if(partiesInfo == null || partiesInfo.size() == 0){
			throw new BusinessException("当前案件缺少当事人信息！");
		}
		CasePartiesInfoVo partInfoVO = partiesInfo.get(Constant.INTEGER_0);
		partInfoVO.setPartyId(null);

		if (stageIds.contains(ReportDataTypeEnum.BASE.getCode())) {
			//上报基础信息
			Result baseResult = this.reportBaseInfo(caseAdditionalRecord, partInfoVO);
		}

		if (stageIds.contains(ReportDataTypeEnum.INFORM.getCode())) {
			//上报处罚告知
			if (!CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
				Result informResult = this.reportInformInfo(caseAdditionalRecord, partInfoVO);
			}
		}

		if (stageIds.contains(ReportDataTypeEnum.DECISION.getCode())) {
			//上报决定信息
			Result decisionResult = this.reportDecisionInfo(caseAdditionalRecord, partInfoVO);
		}

		if (stageIds.contains(ReportDataTypeEnum.EXECUTE.getCode())) {
			//上报执行信息
			Result executeResult = this.reportExecuteInfo(caseAdditionalRecord, partInfoVO);
		}

		if (stageIds.contains(ReportDataTypeEnum.CASE_CLOSED.getCode())) {
			//上报结案信息
			Result closeResult = this.reportCloseInfo(caseAdditionalRecord, partInfoVO);
		}
		//查询上报记录，如果已结案，并且已完成上报个数为5，（如果是决定，并且上报个数是3）则表示已经补录上报成功，需要更新状态
		if(YesOrNoEnum.YES.getCode().equals(updateCaseStatus)){
			Example caseAdditionalExample = new Example(CaseDataReportStageInfo.class);
			caseAdditionalExample.createCriteria().andEqualTo("caseId", caseAdditionalId)
					.andEqualTo("isFinishReport", YesOrNoEnum.YES.getCode());
			int count = caseDataReportStageInfoMapper.selectCountByExample(caseAdditionalExample);
			if(count == 5){
				CaseAdditionalRecord update = new CaseAdditionalRecord();
				update.setId(caseAdditionalId);
				update.setCaseAuditStatus(Constant.STRING_4);
				update.setCaseSuccessTime(LocalDateTime.now());
				caseAdditionalRecordMapper.updateByPrimaryKeySelective(update);
			}
		}
	}

	/**
	 * 上报结案信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @return
	 */
	private Result reportCloseInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO) {
		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();
		try {
			String optType = null;
			String errorMsg;
			String uri = CASE_CLOSED_HTTP;
			JSONObject tmpData = getReportCloseInfo(caseAdditionalRecord, partInfoVO, optType);
			JSONObject reportData = new JSONObject(8);
			reportData.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : tmpData.get("reportActionType"));
			reportData.put("envFlag", tmpData.get("envFlag"));
			tmpData.remove("envFlag");
			tmpData.remove("reportActionType");
			reportData.put("caseClosedInfo", tmpData);
			Map<String, String> params = new HashMap<>(20);
			for (Map.Entry<String, Object> e : reportData.entrySet()) {
				params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
			}
			//组装个caseMainInfo实体类
			CaseMainInfoVo caseMainInfo = new CaseMainInfoVo();
			caseMainInfo.setId(caseAdditionalId);
			errorMsg = caseDataReportRecordService.dataReport(uri, ReportDataTypeEnum.CASE_CLOSED.getCode(), params, caseMainInfo);
			log.info("dataReportClose end");
			if (ObjectUtils.isEmpty(errorMsg)) {
				caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.CASE_CLOSED.getCode(), null, partyId);
				return Result.success("上报成功");
			} else {
				if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.CASE_CLOSED.getCode(), errorMsg, partyId);
				} else if (errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
					//caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
				} else {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.CASE_CLOSED.getCode(), errorMsg, partyId);
				}
				return Result.error(errorMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.CASE_CLOSED.getCode(), e.getMessage(), partyId);
			return Result.error("dataReportClose catch exception：" + e.getMessage());
		}
	}

	/**
	 * 组装结案上报信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @param optType
	 * @return
	 */
	private JSONObject getReportCloseInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO, String optType) {
		JSONObject returnInfo = new JSONObject();
		JSONObject caseClosedInfo = new JSONObject();
		String caseAdditionalId = caseAdditionalRecord.getId();
		String sourceDeptCode = this.getSourceDeptCode(caseAdditionalId);
		String partyId = partInfoVO.getPartyId();
		CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
		queryDto.setCaseId(caseAdditionalId);
		queryDto.setReportDataType(ReportDataTypeEnum.CASE_CLOSED.getCode());
		queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
		queryDto.setPartyId(partyId);
		//默认测试数据1
		String envFlag = Constant.STRING_1;
		if (SpringContextUtil.checkIsPrdProfile()) {
			queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
			envFlag = Constant.STRING_0;
		}

		List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
		String reportActionType = "I";
		if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
			CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
			String latestReportResult = latestRecord.getReportResult();
			if (!Constant.STRING_0.equals(latestReportResult)) {
				String oriActionType = latestRecord.getReportActionType();
				reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
			} else {
				reportActionType = "U";
			}
		}
		String caseType = caseAdditionalRecord.getCaseType();

		caseClosedInfo.put("recordUniqueIdentity", BaseUtil.createUid());

		/*
            如果当事人id为空，则说明是单当事人/多当事人合并处罚，
            则caseId作为 punishBaseInfoCode，
            否则取当事人id作为 punishBaseInfoCode
         */
		String uid = partyId;
		//是否是多当事人分别处罚
		boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId) ? true : false;
		if (!isMultiplePartiesAndPartPunish) {
			uid = caseAdditionalId;
		}
		caseClosedInfo.put("punishBaseInfoCode", uid);
		//结案情况-执行结果[非必填]
		//caseClosedInfo.put("casesClosedExecutionResult",  "");
		//结案实缴罚款金额[非必填]
		//caseClosedInfo.put("casesClosedFine","");
		// FIXME: 2022/4/2 是否涉刑职权案件[当前版本默认否]
		caseClosedInfo.put("isAuthorityCase", Constant.STRING_0);
		//结案情况-不予行政处罚（数据上报规则：0-否/1-是）
		String executeWay = caseAdditionalRecord.getExecuteWay();
		if (!ObjectUtils.isEmpty(executeWay)) {
			caseClosedInfo.put("casesClosedExecution", Constant.STRING_0);
		} else {
			caseClosedInfo.put("casesClosedExecution", Constant.STRING_1);
		}
		//其他处理情况[非必填]
		//caseClosedInfo.put("otherDisposals", "");
		//结案日期
		log.info("caseCloseDate:{}", caseAdditionalRecord.getCaseFinishDate());
		caseClosedInfo.put("caseCloseDate", caseAdditionalRecord.getCaseFinishDate());
		//非正常结案原因 之前省处罚没有涉及：unsusalCloseReason
		//接收部门[非必填]
		//caseClosedInfo.put("receiveDept", "");
		// FIXME: 2022/4/2 移送日期[非必填] 目前无移送日期
		//caseClosedInfo.put("deportationDate", );
		caseClosedInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		caseClosedInfo.put("envFlag", envFlag);
		caseClosedInfo.put("sourceDeptCode", sourceDeptCode);

		returnInfo.put("caseClosedInfo", caseClosedInfo);
		//到dataReport时清空该键值
		returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		returnInfo.put("envFlag", envFlag);
		log.info("collectReportCaseClosedInfo end...result-returnInfo", returnInfo);
		return returnInfo;
	}

	/**
	 * 上报执行信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @return
	 */
	private Result reportExecuteInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO) {
		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();
		try {
			String optType = null;
			String errorMsg = "";
			String uri = EXECUTE_HTTP;
			String reportDataType = ReportDataTypeEnum.EXECUTE.getCode();
			JSONObject tmpData = getReportExecuteInfo(caseAdditionalRecord, partInfoVO, optType);
			JSONObject reportData = new JSONObject(8);
			reportData.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : tmpData.get("reportActionType"));
			reportData.put("envFlag", tmpData.get("envFlag"));
			tmpData.remove("envFlag");
			tmpData.remove("reportActionType");
			reportData.put("executeInfo", tmpData);
			Map<String, String> params = new HashMap<>(20);
			for (Map.Entry<String, Object> e : reportData.entrySet()) {
				params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
			}
			//组装个caseMainInfo实体类
			CaseMainInfoVo caseMainInfo = new CaseMainInfoVo();
			caseMainInfo.setId(caseAdditionalId);
			errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, caseMainInfo);
			log.info("dataReportExecute end");
			if (ObjectUtils.isEmpty(errorMsg)) {
				caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.EXECUTE.getCode(), null, partyId);
				return Result.success("上报成功");
			} else {
				if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.EXECUTE.getCode(), errorMsg, partyId);
				} else if (errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
					//caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
				} else {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.EXECUTE.getCode(), errorMsg, partyId);
				}
				return Result.error(errorMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.EXECUTE.getCode(), e.getMessage(), partyId);
			return Result.error("dataReportExecute catch exception：" + e.getMessage());
		}
	}

	/**
	 * 组装执行信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @param optType
	 * @return
	 */
	private JSONObject getReportExecuteInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO, String optType) {
		JSONObject returnInfo = new JSONObject();
		JSONObject executeInfo = new JSONObject();
		String caseAdditionalId = caseAdditionalRecord.getId();
		String sourceDeptCode = this.getSourceDeptCode(caseAdditionalId);
		CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
		String partyId = partInfoVO.getPartyId();
		queryDto.setCaseId(caseAdditionalId);
		queryDto.setReportDataType(ReportDataTypeEnum.EXECUTE.getCode());
		queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
		queryDto.setPartyId(partyId);
		//默认测试数据1
		String envFlag = Constant.STRING_1;
		if (SpringContextUtil.checkIsPrdProfile()) {
			queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
			envFlag = Constant.STRING_0;
		}

		List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
		String reportActionType = "I";
		if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
			CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
			String latestReportResult = latestRecord.getReportResult();
			if (!Constant.STRING_0.equals(latestReportResult)) {
				String oriActionType = latestRecord.getReportActionType();
				reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
			} else {
				reportActionType = "U";
			}
		}
		String caseType = caseAdditionalRecord.getCaseType();

		executeInfo.put("recordUniqueIdentity", BaseUtil.createUid());

		/*
            如果当事人id为空，则说明是单当事人/多当事人合并处罚，
            则caseId作为 punishBaseInfoCode，
            否则取当事人id作为 punishBaseInfoCode
         */
		String uid = partyId;
		//是否是多当事人分别处罚
		boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId) ? true : false;
		if (!isMultiplePartiesAndPartPunish) {
			uid = caseAdditionalId;
		}
		executeInfo.put("punishBaseInfoCode", uid);

		//是否执行处罚决定
		String isExecutePunish = caseAdditionalRecord.getIsExecutePunish();
		executeInfo.put("isExecute", isExecutePunish);
		if(YesOrNoEnum.NO.getCode().equals(isExecutePunish)){//未执行处罚决定
			//未执行处罚决定原因
			executeInfo.put("noExecutionReason", caseAdditionalRecord.getIsExecutePunish());
		}else {//已执行
			String executeWay = caseAdditionalRecord.getExecuteWay();
			//执行类型，自觉履行：executionType=1，强制执行：executionType=2
			String executionType = Constant.STRING_1;
			if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {//简易处罚默认自觉履行
				//简易处罚
				executeWay = "自觉履行";
			}
			executeInfo.put("executionFinishDate", caseAdditionalRecord.getCaseFinishDate().toLocalDate());
			//自觉履行：executionType=1，强制执行：executionType=2
			if("强制执行".equals(executeWay)){
				executionType = Constant.STRING_2;
			}
			executeInfo.put("executionType", executionType);
			//是否分期
			executeInfo.put("isStaging", caseAdditionalRecord.getIsStages());
			//是否延期
			executeInfo.put("isExtention", caseAdditionalRecord.getIsDelay());
		}
		//处罚结果
		executeInfo.put("penaltyResult", caseAdditionalRecord.getCasePunishResult());

		executeInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		executeInfo.put("envFlag", envFlag);
		executeInfo.put("sourceDeptCode", sourceDeptCode);
		returnInfo.put("executeInfo", executeInfo);
		//到dataReport时清空该键值
		returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		returnInfo.put("envFlag", envFlag);
		log.info("collectReportCaseExecuteInfo end...result-returnInfo", returnInfo);
		return returnInfo;
	}

	/**
	 * 上报决定信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @return
	 */
	private Result reportDecisionInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO) {
		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();
		try {
			String optType = null;
			String errorMsg = "";
			//根据案件id查询案件信息
			String uri = DECISION_HTTP;
			String reportDataType = ReportDataTypeEnum.DECISION.getCode();
			JSONObject tmpData = getReportDecisionInfo(caseAdditionalRecord, partInfoVO, false, optType);
			JSONObject reportData = new JSONObject(8);
			reportData.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : tmpData.get("reportActionType"));
			reportData.put("envFlag", tmpData.get("envFlag"));
			tmpData.remove("envFlag");
			tmpData.remove("reportActionType");
			reportData.put("decisionInfo", tmpData);
			Map<String, String> params = new HashMap<>(20);
			for (Map.Entry<String, Object> e : reportData.entrySet()) {
				params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
			}
			//组装个caseMainInfo实体类
			CaseMainInfoVo caseMainInfo = new CaseMainInfoVo();
			caseMainInfo.setId(caseAdditionalId);
			errorMsg = caseDataReportRecordService.dataReport(uri, reportDataType, params, caseMainInfo);
			log.info("dataReportDecision end");
			if (ObjectUtils.isEmpty(errorMsg)) {
				caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.DECISION.getCode(), null, partyId);
				//上报成功更新公示时间
				updatePublicDateAndUrl(caseAdditionalId, tmpData);
				return Result.success("上报成功");
			} else {
				if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.DECISION.getCode(), errorMsg, partyId);
					//上报成功更新公示时间
					updatePublicDateAndUrl(caseAdditionalId, tmpData);
				} else if (errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
					//caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
				} else {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.DECISION.getCode(), errorMsg, partyId);
				}
				return Result.error(errorMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.DECISION.getCode(), e.getMessage(), partyId);
			return Result.error("dataReportDecision catch exception：" + e.getMessage());
		}
	}

	/**
	 * 组装决定信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @param isUpdateReReport
	 * @param optType
	 * @return
	 */
	private JSONObject getReportDecisionInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO, boolean isUpdateReReport, String optType) {
		JSONObject returnInfo = new JSONObject();
		JSONObject decisionInfo = new JSONObject();

		String caseAdditionalId = caseAdditionalRecord.getId();
		String sourceDeptCode = this.getSourceDeptCode(caseAdditionalId);
		String partyId = partInfoVO.getPartyId();
		CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
		queryDto.setCaseId(caseAdditionalId);
		queryDto.setReportDataType(ReportDataTypeEnum.DECISION.getCode());
		queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
		queryDto.setPartyId(partyId);
		//默认测试数据1
		String envFlag = Constant.STRING_1;
		if (SpringContextUtil.checkIsPrdProfile()) {
			queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
			envFlag = Constant.STRING_0;
		}
		List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
		String reportActionType = "I";
		if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
			CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
			String latestReportResult = latestRecord.getReportResult();
			if (!Constant.STRING_0.equals(latestReportResult)) {
				String oriActionType = latestRecord.getReportActionType();
				reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
			} else {
				reportActionType = "U";
			}
		}
		if (isUpdateReReport) {
			reportActionType = "U";
		}

		//是否重大案件
		String isImportantCase = caseAdditionalRecord.getIsImportantCase();
		decisionInfo.put("recordUniqueIdentity", BaseUtil.createUid());

		/*
            如果当事人id为空，则说明是单当事人/多当事人合并处罚，
            则caseId作为 punishBaseInfoCode，
            否则取当事人id作为 punishBaseInfoCode
         */
		String uid = partyId;
		//是否是多当事人分别处罚
		boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId) ? true : false;
		if (!isMultiplePartiesAndPartPunish) {
			uid = caseAdditionalId;
		}
		decisionInfo.put("punishBaseInfoCode", uid);


		String illegalFact = caseAdditionalRecord.getIllegalFact();
		String punishKind = caseAdditionalRecord.getPunishKinds();
		//没收非法财物金额
		String confiscateIllegalPunishMoney = caseAdditionalRecord.getConfiscateIllegalPunishMoney();
		//没收违法所得
		String confiscateIllegalMoney = caseAdditionalRecord.getConfiscatePunishMoney();
		//拟处罚金额
		String draftPunishMoney = caseAdditionalRecord.getDraftPunishMoney();
		String isPublicity = caseAdditionalRecord.getIsPublicity();
		String publicText = caseAdditionalRecord.getPublicityContent();
		String punishContent = caseAdditionalRecord.getCasePunishResult();

		String punishDocumentCode = caseAdditionalRecord.getDocumentNumber();
		String investConclusion = caseAdditionalRecord.getCaseDocumentCategory();

		//是否集体议案（数据上报规则：0-否/1-是）
		String isGroupDiscuss = caseAdditionalRecord.getIsNeedCollectiveDiscuss();
		LocalDateTime caseHappenTime = caseAdditionalRecord.getCaseHappenTime();

		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
			//20220927 简易处罚案件不公示
			isPublicity = YesOrNoEnum.NO.getCode();
			String punishDesc;
			//简易程序的展示处罚种类，若罚款的展示罚款金额。
			if ("罚款".equals(punishKind)) {
				punishDesc = "罚款" + draftPunishMoney + "元";
			} else if (punishKind.contains("罚款") && punishKind.contains("警告")) {
				punishDesc = "警告并罚款" + draftPunishMoney + "元";
			} else {
				punishDesc = caseAdditionalRecord.getPunishKinds();
			}
			punishContent = punishDesc;
			isGroupDiscuss = YesOrNoEnum.NO.getCode();
			punishDocumentCode = caseAdditionalRecord.getDocumentNumber();
			publicText = "";
			investConclusion = "";
		}

		decisionInfo.put("isMajorCase", ObjectUtils.isEmpty(isImportantCase) ? YesOrNoEnum.NO.getCode() : isImportantCase);

		//判断是否法制审核
		decisionInfo.put("isLegalReview", caseAdditionalRecord.getIsDocumentAudit());
		if (YesOrNoEnum.YES.getCode().equals(caseAdditionalRecord.getIsDocumentAudit())) {
			//法制审核日期
			decisionInfo.put("legalReviewDate", caseAdditionalRecord.getDocumentAuditDate());
			//法制审核意见
			decisionInfo.put("legalReviewOpinions", "同意");
		}

		decisionInfo.put("isGroupDiscuss", isGroupDiscuss);
		if (YesOrNoEnum.YES.getCode().equals(isGroupDiscuss)) {
			//TODO：应数浙要求，该字段数据上报格式取消下划线，线上验证通过后，取消该注释 20221129
			decisionInfo.put("groupDiscussionDate", caseAdditionalRecord.getNeedCollectiveDiscussTime());
			decisionInfo.put("groupDiscussionConclusion", caseAdditionalRecord.getNeedCollectiveDiscussReason());
		}
		decisionInfo.put("illegalFact", illegalFact);
		CaseReasonMainRecordVo caseReasonMainRecord = caseReasonMainRecordService.getCaseReasonRecordByCaseId(caseAdditionalRecord.getId());
		if (ObjectUtils.isEmpty(caseReasonMainRecord)) {
			throw new DataReportException("collectReportCaseDecisionInfo 未找到案件案由记录信息,caseId:" + caseAdditionalRecord.getId());
		} else {
			decisionInfo.put("illegalBasis", caseReasonMainRecord.getIllegalBasis());
			decisionInfo.put("punishBasis", caseReasonMainRecord.getPunishBasis());
		}

		String decisionType = "01";
		if (Constant.STRING_2.equals(investConclusion)) {
			//不予处罚
			decisionType = "02";
		}
		decisionInfo.put("decisionType", decisionType);

		String punishType = "";
		Map<String, String> punishTypeMap = new HashMap<>(16);
		punishTypeMap.put("警告", "01");
		punishTypeMap.put("罚款", "02");
		punishTypeMap.put("没收违法所得", "03");
		punishTypeMap.put("没收非法财物", "03");
		punishTypeMap.put("责令停产停业", "04");
		punishTypeMap.put("暂扣或者吊销许可证、暂扣或者吊销执照", "05");
		punishTypeMap.put("吊销许可证", "05");
		punishTypeMap.put("行政拘留", "06");
		punishTypeMap.put("其他", "07");
		if (!ObjectUtils.isEmpty(punishKind)) {
			String[] punishKindArr = punishKind.split(",");
			for (String s : punishKindArr) {
				String value = punishTypeMap.get(s);
				if (ObjectUtils.isEmpty(value)) {
					punishType += "07^";
				} else {
					punishType += value + "^";
				}

			}
		} else {
			//默认为07【正常业务逻辑不可能出现为空】
			punishType = "07";
		}
		if (punishType.endsWith("^")) {
			punishType = punishType.substring(0, punishType.length() - 1);
		}
		decisionInfo.put("punishType", punishType);
		decisionInfo.put("punishContent", ObjectUtils.isEmpty(punishContent) ? Constant.STRING_HORIZONTAL_BARS : punishContent);

		//罚款金额
		String fine = "0.00";
		String confiscateIllegalIncom = "0.00";
		String confiscateIllegalAsset = "0.00";

		double confiscateIllegalMoneyD = 0D;
		double draftPunishMoneyD = 0D;
		double confiscateIllegalPunishMoneyD = 0D;
		if (!ObjectUtils.isEmpty(confiscateIllegalMoney)) {
			confiscateIllegalMoneyD = Double.parseDouble(confiscateIllegalMoney);
		}
		if (!ObjectUtils.isEmpty(draftPunishMoney)) {
			draftPunishMoneyD = Double.parseDouble(draftPunishMoney);
		}
		if (!ObjectUtils.isEmpty(confiscateIllegalPunishMoney)) {
			confiscateIllegalPunishMoneyD = Double.parseDouble(confiscateIllegalPunishMoney);
		}
		//罚款金额总计
		/*double totalPunishMoney = confiscateIllegalMoneyD + draftPunishMoneyD;
		if (totalPunishMoney > 0) {
			fine = String.valueOf(totalPunishMoney);
			confiscateIllegalIncom = fine;
		}*/
		if(draftPunishMoneyD > 0){
			fine = String.valueOf(draftPunishMoneyD);
		}
		if(confiscateIllegalMoneyD > 0){
			confiscateIllegalIncom = String.valueOf(confiscateIllegalMoneyD);
		}
		if(confiscateIllegalPunishMoneyD > 0){
			confiscateIllegalAsset = String.valueOf(confiscateIllegalPunishMoneyD);
		}
		decisionInfo.put("fine", fine);
		decisionInfo.put("confiscateIllegalIncom", confiscateIllegalIncom);
		decisionInfo.put("confiscateIllegalAsset", confiscateIllegalAsset);

		if (punishType.contains("06")) {
			decisionInfo.put("detainDays", caseAdditionalRecord.getCaseDetentionDay());
			decisionInfo.put("detainStartDate", caseAdditionalRecord.getCaseDetentionStartTime());
			decisionInfo.put("detainEndDate", caseAdditionalRecord.getCaseDetentionEndTime());
		} else {
			decisionInfo.put("detainDays", "0");
			decisionInfo.put("detainStartDate", null);
			decisionInfo.put("detainEndDate", null);
		}
		if (punishTypeMap.containsKey("其他")) {
			decisionInfo.put("otherContent", "-");
		} else {
			decisionInfo.put("otherContent", "");
		}

		decisionInfo.put("setTime", caseAdditionalRecord.getDecisionSentTime());

		//决定书文号
		decisionInfo.put("punishDocumentCode", punishDocumentCode);
		//决定书 互联网地址
		Example example = new Example(CaseAppendixRecord.class);
		example.createCriteria().andEqualTo("isDelete", "0").andEqualTo("caseId", caseAdditionalRecord.getId());
		List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(example);
		String url = "";
		if (caseAppendixRecords != null && caseAppendixRecords.size() > 0) {
			for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
				if (caseAppendixRecord.getAppendixUrl().contains(".pdf")) {
					url = caseAppendixRecord.getAppendixUrl();
					break;
				}
			}
		}
		decisionInfo.put("punishDocument", StrUtil.isEmpty(url) ? Constant.STRING_HORIZONTAL_BARS : url);
		//简易处罚送达时间用结案时间
		LocalDateTime deliverDate = caseAdditionalRecord.getDecisionSentTime();
		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
			deliverDate = caseAdditionalRecord.getCaseFinishDate();
		}
		decisionInfo.put("deliverDate", deliverDate);

		//默认电子送达
		String deliverMode = "06";
		Map<String, String> sentWayMap = new HashMap<>(8);
		sentWayMap.put("直接送达", "01");
		sentWayMap.put("留置送达", "02");
		sentWayMap.put("委托送达", "03");
		sentWayMap.put("邮递送达", "04");
		sentWayMap.put("公告送达", "05");
		sentWayMap.put("其他方式送达", "99");
		sentWayMap.put("电子送达", "06");
		//默认电子送达
		String sendWayName = SendWayEnum.getValueByCode(caseAdditionalRecord.getDecisionSentWay());
		deliverMode = ObjectUtils.isEmpty(sentWayMap.get(sendWayName)) ? deliverMode : sentWayMap.get(sendWayName);
		decisionInfo.put("deliverMode", deliverMode);

		String isPublic = Constant.STRING_1;
		if (Constant.STRING_0.equals(isPublicity)) {
			isPublic = Constant.STRING_0;
		}
		//20220927 简易处罚案件不公示
		decisionInfo.put("isPublic", isPublic);
		//decisionInfo.put("ppSentDate", jgCase.getExtraInfo().getXzcfjd());
		//20220726-公示时间由系统当前时间改成送达时间
		decisionInfo.put("publicDate", caseAdditionalRecord.getDecisionSentTime());
		if (punishType.contains("05")) {
			decisionInfo.put("isRevoked", YesOrNoEnum.YES.getCode());
			decisionInfo.put("revokeLicenceName", "-");
			decisionInfo.put("revokeLicenceCode", "-");
			// FIXME: 2022/11/30 暂时用送达时间来代替，目前没有这块业务
			decisionInfo.put("detainCertStartDate", caseAdditionalRecord.getDecisionSentTime());
			decisionInfo.put("detainCertEndDate", caseAdditionalRecord.getDecisionSentTime());
		} else {
			decisionInfo.put("isRevoked", "0");
		}

		if (ObjectUtils.isEmpty(publicText)) {
			//兜底方案
			StringBuilder tmpTxt = new StringBuilder();
			CasePartiesDetailInfoVo vo = casePartiesRecordService.getCaseAdditionalPartiesDetailInfo(caseAdditionalRecord.getId());
			if (ObjectUtils.isEmpty(vo)) {
				throw new DataReportException("未找到当事人信息 caseId:" + caseAdditionalRecord.getId());
			}
			String partyName;
			if (PartyTypeEnum.PERSON.getCode().equals(vo.getPartyType())) {
				partyName = vo.getCasePartiesPersonInfo().getName();
			} else {
				partyName = vo.getCasePartiesLegalInfo().getEntName();
			}
			tmpTxt.append(partyName);
			tmpTxt.append("于");


			if (!ObjectUtils.isEmpty(caseHappenTime)) {
				String time = caseHappenTime.toLocalDate().toString();
				tmpTxt.append(time);
			} else {
				tmpTxt.append(" ");
			}
			tmpTxt.append("在");
			//案件补录表中没有发生案件地址
			tmpTxt.append("-");
			tmpTxt.append("实施了");
			tmpTxt.append(caseReasonMainRecord.getCaseReasonNameSimple());
			tmpTxt.append("的行为，违反了");
			tmpTxt.append(caseReasonMainRecord.getIllegalBasisFormat());
			tmpTxt.append("，依据");
			tmpTxt.append(caseReasonMainRecord.getPunishBasisFormat());
			tmpTxt.append(",作出如下行政处罚：");
			String casePunishContent = ObjectUtils.isEmpty(punishContent) ? "-" : punishContent;
			tmpTxt.append(casePunishContent);
			publicText = tmpTxt.toString();
		}

		decisionInfo.put("publicText", publicText);
		//公示状态（正常、撤销、删除）-0:正常，1：撤销，2：删除
		decisionInfo.put("publicStatus", "0");
		decisionInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		decisionInfo.put("envFlag", envFlag);
		decisionInfo.put("sourceDeptCode", sourceDeptCode);
		returnInfo.put("decisionInfo", decisionInfo);
		//到dataReport时清空该键值
		returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		returnInfo.put("envFlag", envFlag);
		log.info("collectReportCaseDecisionInfo end...result-returnInfo", returnInfo);
		return returnInfo;
	}

	/**
	 * 上报告知信息
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @return
	 */
	private Result reportInformInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO) {
		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();
		try {
			String optType = null;
			String errorMsg = "";
			String uri = INFORM_HTTP;
			JSONObject tmpData = getReportInformInfo(caseAdditionalRecord, ReportDataTypeEnum.INFORM.getCode(), partInfoVO, optType);
			JSONObject reportData = new JSONObject(8);
			reportData.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : tmpData.get("reportActionType"));
			reportData.put("envFlag", tmpData.get("envFlag"));
			tmpData.remove("envFlag");
			tmpData.remove("reportActionType");
			reportData.put("informInfo", tmpData);
			Map<String, String> params = new HashMap<>(20);
			for (Map.Entry<String, Object> e : reportData.entrySet()) {
				params.put(e.getKey(), (ObjectUtils.isEmpty(e.getValue()) ? "" : e.getValue().toString()));
			}
			//组装个caseMainInfo实体类
			CaseMainInfoVo caseMainInfo = new CaseMainInfoVo();
			caseMainInfo.setId(caseAdditionalId);
			errorMsg = caseDataReportRecordService.dataReport(uri, ReportDataTypeEnum.INFORM.getCode(), params, caseMainInfo);
			log.info("dataReportInform end");
			if (ObjectUtils.isEmpty(errorMsg)) {
				caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.INFORM.getCode(), null, partyId);
				return Result.success("上报成功");
			} else {
				if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.INFORM.getCode(), errorMsg, partyId);
				} else if (errorMsg.contains(Constant.STRING_ERROR_SIGN)) {
					//caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, reportDataType);
				} else {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.INFORM.getCode(), errorMsg, partyId);
				}
				return Result.error(errorMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.INFORM.getCode(), e.getMessage(), partyId);
			return Result.error("dataReportInform catch exception：" + e.getMessage());
		}
	}

	/**
	 * 组装上报告知信息
	 *
	 * @param caseAdditionalRecord
	 * @param reportDataType
	 * @param partyInfo
	 * @param optType
	 * @return
	 */
	private JSONObject getReportInformInfo(CaseAdditionalRecord caseAdditionalRecord, String reportDataType, CasePartiesInfoVo partyInfo, String optType) {
		JSONObject returnInfo = new JSONObject();
		JSONObject informInfo = new JSONObject();

		String caseAdditionalId = caseAdditionalRecord.getId();
		String sourceDeptCode = this.getSourceDeptCode(caseAdditionalId);
		CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
		String partyId = partyInfo.getPartyId();
		queryDto.setCaseId(caseAdditionalId);
		queryDto.setReportDataType(reportDataType);
		queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
		queryDto.setPartyId(partyId);
		//默认测试数据1
		String envFlag = Constant.STRING_1;
		if (SpringContextUtil.checkIsPrdProfile()) {
			queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
			envFlag = Constant.STRING_0;
		}

		List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
		String reportActionType = "I";
		if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
			CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
			String latestReportResult = latestRecord.getReportResult();
			if (!Constant.STRING_0.equals(latestReportResult)) {
				String oriActionType = latestRecord.getReportActionType();
				reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
			} else {
				reportActionType = "U";
			}
		}
		informInfo.put("recordUniqueIdentity", BaseUtil.createUid());

		String uid = partyId;
		//是否是多当事人分别处罚
		boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId) ? true : false;
		if (!isMultiplePartiesAndPartPunish) {
			uid = caseAdditionalId;
		}
		informInfo.put("punishBaseInfoCode", uid);

		String punishKind = caseAdditionalRecord.getPunishKinds();
		//没有调查取证日期，取立案日期代替
		informInfo.put("investigateEndDate", caseAdditionalRecord.getCaseRegistTime() + "");

		/*
        告知方式：
        数据上报规则：
            01-口头
            02-书面
         */
		informInfo.put("informMode", "02");

		informInfo.put("informPunishType", this.getInformPunishType(punishKind));
		// FIXME: 2022/4/1 目前是否听证默认否（1-需要听证/0-不需要听证/-1-无该流程）
		informInfo.put("ifHearingWitnesses", Constant.STRING_0);

		//告知书的送达时间和审批通过时间
		informInfo.put("deliverTime", caseAdditionalRecord.getSentTime());
		informInfo.put("informDate", caseAdditionalRecord.getSentTime());

		//获取送达方式
		//送达方式
		informInfo.put("deliverMode", this.getSentWay(caseAdditionalRecord.getSendWay()));

		informInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		informInfo.put("envFlag", envFlag);
		informInfo.put("sourceDeptCode", sourceDeptCode);
		returnInfo.put("informInfo", informInfo);
		//到dataReport时清空该键值
		returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		returnInfo.put("envFlag", envFlag);
		log.info("collectReportCaseInformInfo end...result-returnInfo", returnInfo);
		return returnInfo;
	}

	/**
	 * 获取送达方式
	 *
	 * @param sendWay
	 * @return
	 */
	private String getSentWay(String sendWay) {
		String deliverMode = "06";
		Map<String, String> sentWayMap = new HashMap<>(8);
		sentWayMap.put("直接送达", "01");
		sentWayMap.put("留置送达", "02");
		sentWayMap.put("委托送达", "03");
		sentWayMap.put("邮递送达", "04");
		sentWayMap.put("公告送达", "05");
		sentWayMap.put("其他方式送达", "99");
		sentWayMap.put("电子送达", "06");
		String sentWayName = SendWayEnum.getValueByCode(sendWay);
		//默认电子送达
		deliverMode = ObjectUtils.isEmpty(sentWayMap.get(sentWayName)) ? deliverMode : sentWayMap.get(sentWayName);
		return deliverMode;
	}

	/**
	 * 获取处罚类型
	 *
	 * @param punishKind
	 * @return
	 */
	private String getInformPunishType(String punishKind) {
		//获取处罚告知种类
		String informPunishType = "";
		Map<String, String> punishTypeMap = new HashMap<>(16);
		punishTypeMap.put("警告", "01");
		punishTypeMap.put("罚款", "02");
		punishTypeMap.put("没收违法所得、没收非法财物", "03");
		punishTypeMap.put("责令停产停业", "04");
		punishTypeMap.put("暂扣或者吊销许可证、暂扣或者吊销执照", "05");
		punishTypeMap.put("吊销许可证", "05");
		punishTypeMap.put("行政拘留", "06");
		punishTypeMap.put("其他", "99");
		if (!ObjectUtils.isEmpty(punishKind)) {
			String[] punishKindArr = punishKind.split(",");
			for (String s : punishKindArr) {
				String value = punishTypeMap.get(s);
				if (ObjectUtils.isEmpty(value)) {
					informPunishType += "99^";
				} else {
					informPunishType += value + "^";
				}
			}
		} else {
			//默认为99【正常业务逻辑不可能出现为空】
			informPunishType = "99";
		}
		if (informPunishType.endsWith("^")) {
			informPunishType = informPunishType.substring(0, informPunishType.length() - 1);
		}
		return informPunishType;
	}


	/**
	 * 上报基础信息
	 *
	 * @param caseAdditionalRecord
	 * @return
	 */
	private Result reportBaseInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO) {
		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();
		try {
			String optType = null;
			String errorMsg = "";
			String uri = BASE_HTTP;

			JSONObject reportData = getReportBaseInfo(caseAdditionalRecord, partInfoVO, false, optType);
			Map<String, String> params = new HashMap<>(2);
			params.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportData.getString("reportActionType"));
			params.put("envFlag", reportData.getString("envFlag"));
			params.put("baseInfo", reportData.toJSONString());
			//组装个caseMainInfo实体类
			CaseMainInfoVo caseMainInfo = new CaseMainInfoVo();
			caseMainInfo.setId(caseAdditionalId);
			errorMsg = caseDataReportRecordService.dataReport(uri, ReportDataTypeEnum.BASE.getCode(), params, caseMainInfo);

			log.info("dataReportBase end");
			if (ObjectUtils.isEmpty(errorMsg)) {
				caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.BASE.getCode(), null, partyId);
				return Result.success("上报成功");
			} else {
				if (errorMsg.contains(Constant.STRING_RECORD_EXISTS)) {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, true, ReportDataTypeEnum.BASE.getCode(), errorMsg, partyId);
					return Result.success("上报成功");
				} else if (errorMsg.contains(Constant.STRING_ERROR_SIGN)) {//暂时不用重试机制
					//caseDataReportRecordService.reportAgain(dto, partyInfo, caseMainInfo, this, ReportDataTypeEnum.BASE.getCode());
				} else {
					caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.BASE.getCode(), errorMsg, partyId);
				}
				return Result.error(errorMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			caseDataReportStageInfoService.dealAfterReport(caseAdditionalId, false, ReportDataTypeEnum.BASE.getCode(), e.getMessage(), partyId);
			return Result.error("dataReportBase catch exception：" + e.getMessage());
		}
	}


	/**
	 * 判断是否允许数据上报
	 *
	 * @param caseAdditionalRecord
	 */
	private void judgeAllowDataReport(CaseAdditionalRecord caseAdditionalRecord) {
		String orgCode = caseAdditionalRecord.getOrgCode();
		if (StrUtil.isEmpty(orgCode)) {
			throw new BusinessException("当前案件机构编码缺失，无法上报！");
		}
		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType()) && orgCode.startsWith("3310")) {
			throw new BusinessException("当前案件暂不支持数据上报！");
		}
		//判断是否开启数据上报
		SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode, "");
		if (YesOrNoEnum.NO.getCode().equals(sysDepartParam.getIsAllowDataReport())) {
			throw new BusinessException("该部门是否允许上报数据按钮处于关闭状态");
		}
	}

	/**
	 * 判断是否允许数据上报
	 *
	 * @param caseAdditionalRecord
	 */
	private boolean judgeIsAllowDataReport(CaseAdditionalRecord caseAdditionalRecord) {
		boolean flag = true;
		String orgCode = caseAdditionalRecord.getOrgCode();
		if (StrUtil.isEmpty(orgCode)) {
			flag = false;
		}
		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType()) && orgCode.startsWith("3310")) {
			flag = false;
		}
		//判断是否开启数据上报
		SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode, "");
		if (YesOrNoEnum.NO.getCode().equals(sysDepartParam.getIsAllowDataReport())) {
			flag = false;
		}
		return flag;
	}


	/**
	 * 组装上报数据
	 *
	 * @param caseAdditionalRecord
	 * @param partInfoVO
	 * @param isUpdateReReport
	 * @param optType
	 * @return
	 */
	private JSONObject getReportBaseInfo(CaseAdditionalRecord caseAdditionalRecord, CasePartiesInfoVo partInfoVO, boolean isUpdateReReport, String optType) {
		JSONObject returnInfo = new JSONObject();
		JSONObject baseInfo = new JSONObject();
		String uid = partInfoVO.getPartyId();
		if (StrUtil.isEmpty(partInfoVO.getPartyId())) {
			uid = caseAdditionalRecord.getId();
		}
		baseInfo.put("recordUniqueIdentity", uid);
		//案件编号
		baseInfo.put("punishCaseCode", caseAdditionalRecord.getCaseNumber());
		baseInfo.put("punishActionName", caseAdditionalRecord.getCaseName());
		baseInfo.put("implementInstitution", caseAdditionalRecord.getOrgName());
		baseInfo.put("implementInstitutionCode", caseAdditionalRecord.getUnicode());
		//传带下划线的orgCode会导致无法公示，而该orgCode是易和的组织编码的含义，这个还需要配置（但是目前浙江政务网对这块没有特殊要求）
		String areaCode = this.getAreaCode(caseAdditionalRecord);
		String orgCode = areaCode;
		if("330000000000_11330000002482154N".equals(caseAdditionalRecord.getOrgCode())){
			orgCode = "001003011";
		}
		baseInfo.put("orgCode", orgCode);
		baseInfo.put("adminiDivisionCode", areaCode);
		// FIXME: 2022/3/31 目前写死"否"
		baseInfo.put("isEntrust", YesOrNoEnum.NO.getCode());
		baseInfo.put("caseProcessType", this.getCaseTypeCode(caseAdditionalRecord.getCaseType()));
		String caseSourceCode = this.getCaseResourceCode(caseAdditionalRecord.getCaseSource());
		baseInfo.put("caseSourceType", caseSourceCode);

		//日期格式测试后，再按需调整
		baseInfo.put("caseSourceDate", caseAdditionalRecord.getCaseHappenTime() + "");

		//移送部门信息
		if ("06".equals(caseSourceCode)) {
			String transferUnitName = caseAdditionalRecord.getCaseOrgName();
			String transferUnitUniscid = caseAdditionalRecord.getCaseOrgCode();
			baseInfo.put("deportationDeptName", transferUnitName);
			baseInfo.put("deportationDeptCode", transferUnitUniscid);
		}
		//设置当事人信息
		this.setPartyInfo(baseInfo, partInfoVO);
		//执法人员信息
		baseInfo.put("punishPersonnelName", caseAdditionalRecord.getNameList());
		baseInfo.put("punishPersonnelCode", caseAdditionalRecord.getCaseLerepCode());

		if (!ObjectUtils.isEmpty(caseAdditionalRecord.getCaseRegistTime())) {
			baseInfo.put("isFiling", Constant.STRING_1);
		} else {
			baseInfo.put("isFiling", Constant.STRING_0);
		}
		//条线信息，必传（）
		String sourceDeptCode = this.getSourceDeptCode(caseAdditionalRecord.getId());
		baseInfo.put("sourceDeptCode", sourceDeptCode);

		String partyId = partInfoVO.getPartyId();
		String caseAdditionalId = caseAdditionalRecord.getId();

		//获取caseId+reportDataType+isTestData 对应记录
		CaseDataReportRecordQueryDto queryDto = new CaseDataReportRecordQueryDto();
		queryDto.setCaseId(caseAdditionalId);
		queryDto.setReportDataType(ReportDataTypeEnum.BASE.getCode());
		queryDto.setIsTestData(YesOrNoEnum.YES.getCode());
		queryDto.setPartyId(partyId);
		//默认测试数据1
		String envFlag = Constant.STRING_1;
		if (SpringContextUtil.checkIsPrdProfile()) {
			queryDto.setIsTestData(YesOrNoEnum.NO.getCode());
			envFlag = Constant.STRING_0;
		}
		List<CaseDataReportRecordVo> list = caseDataReportRecordService.getCaseDataReportRecord(queryDto);
		//基础信息数据上报类型（I-新增/U-更新）

		String isBasicInfoExists = "I";
		//事项信息数据上报类型（I-新增/U-更新）
		String isItemInfoExists = "I";

		String reportActionType = "I";
		if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
			CaseDataReportRecordVo latestRecord = list.get(Constant.INTEGER_0);
			String latestReportResult = latestRecord.getReportResult();
			if (!Constant.STRING_0.equals(latestReportResult)) {
				//失败
				String oriActionType = latestRecord.getReportActionType();
				reportActionType = "U".equals(oriActionType) ? oriActionType : "I";
                /*
                    如果存在未完成且 reportFailReason like '该条数据已存在',则将optType调整为U;
                    -[基础信息]该条数据已经存在
                    -[事项信息]该条数据已经存在
                 */
				String reportFailReason = latestRecord.getReportFailReason();
				if (!ObjectUtils.isEmpty(reportFailReason)) {
					if (reportFailReason.contains("[基础信息]该条数据已经存在")) {
						isBasicInfoExists = "U";
					} else if (reportFailReason.contains("[事项信息]该条数据已经存在")) {
						isItemInfoExists = "U";
					}
				}

			} else {
				reportActionType = "U";
			}
		}
		if (isUpdateReReport) {
			reportActionType = "U";
		}
		String totalOptType = "I";
		if ("U".equals(isBasicInfoExists) || "U".equals(isItemInfoExists)) {
			totalOptType = "U";
		}
		//判断是否为更新
		CaseDataReportStageInfoQueryDto query = new CaseDataReportStageInfoQueryDto();
		query.setReportStageTag(ReportDataTypeEnum.BASE.getCode());
		query.setIsFinishReport(YesOrNoEnum.YES.getCode());
		query.setPartyId(partyId);
		query.setCaseId(caseAdditionalId);
		List<CaseDataReportStageInfoVo> listStage = caseDataReportStageInfoService.getCaseDataReportStageInfoList(query);
		if ("I".equals(totalOptType) && listStage.size() > 0) {
			totalOptType = "U";
		}
		baseInfo.put("optType", !ObjectUtils.isEmpty(optType) ? optType : totalOptType);
		//非必填
		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseAdditionalRecord.getCaseType())) {
			baseInfo.put("isHandCase", "1");
		}
		returnInfo.put("baseInfo", baseInfo);

		JSONArray itemInfo = collectItemInfo(caseAdditionalId, (totalOptType), envFlag, sourceDeptCode, partyId);
		JSONObject filingInfo = new JSONObject();

		//构造立案文书号/立案批准人
		filingInfo.put("recordUniqueIdentity", BaseUtil.createUid());

		filingInfo.put("punishBaseInfoCode", uid);
		//立案批准日期
		filingInfo.put("filingDate", caseAdditionalRecord.getCaseRegistTime() + "");
		//立案批准人[非必填]
		//filingInfo.put("filingPerson","");
		//立案文书号[非必填]
		filingInfo.put("filingCode", caseAdditionalRecord.getCaseNumber());

		filingInfo.put("optType", totalOptType);
		filingInfo.put("envFlag", envFlag);
		filingInfo.put("sourceDeptCode", sourceDeptCode);

		returnInfo.put("superviseItemInfoList", itemInfo);
		returnInfo.put("filingInfo", filingInfo);
		//到dataReport时清空该键值
		returnInfo.put("reportActionType", !ObjectUtils.isEmpty(optType) ? optType : reportActionType);
		returnInfo.put("envFlag", envFlag);

		log.info("reportDataCollect end...result-returnInfo:{}", returnInfo);
		return returnInfo;


	}


	/**
	 * 案由相关处理
	 *
	 * @param caseId
	 * @param optType
	 * @param envFlag
	 * @param sourceDeptCode
	 * @param partyId
	 * @return
	 */
	private JSONArray collectItemInfo(String caseId, String optType, String envFlag, String sourceDeptCode, String partyId) {
		log.info("collectItemInfo start...param-caseId:{},optType:{},envFlag:{},sourceDeptCode:{}",
				caseId, optType, envFlag, sourceDeptCode);
		JSONArray jsonArray = new JSONArray();
		CaseReasonMainRecordQueryDto queryDto = new CaseReasonMainRecordQueryDto();
		queryDto.setCaseId(caseId);
		List<CaseReasonMainRecordVo> caseReasonMainRecordList = caseReasonMainRecordService.getCaseReasonRecordList(queryDto);
        /*
            如果当事人id为空，则说明是单当事人/多当事人合并处罚，
            则caseId作为 punishBaseInfoCode，
            否则取当事人id作为 punishBaseInfoCode
         */
		String uid = partyId;
		//是否是多当事人分别处罚
		boolean isMultiplePartiesAndPartPunish = !ObjectUtils.isEmpty(partyId) ? true : false;
		if (!isMultiplePartiesAndPartPunish) {
			uid = caseId;
		}
		for (CaseReasonMainRecordVo record : caseReasonMainRecordList) {
			JSONObject item = new JSONObject();
			item.put("recordUniqueIdentity", BaseUtil.createUid());
			item.put("punishBaseInfoCode", uid);
			item.put("superviseItemCode", record.getCaseReasonCode());
			item.put("superviseItemName", record.getCaseReasonName());
			item.put("optType", optType);
			item.put("envFlag", envFlag);
			item.put("sourceDeptCode", sourceDeptCode);
			jsonArray.add(item);
		}
		// FIXME: 2022/3/31 待校验日志输出的合理性
		log.info("collectItemInfo end...result:{}", jsonArray);
		return jsonArray;
	}

	/**
	 * 获取案由
	 *
	 * @param caseAdditionalId
	 * @return
	 */
	private String getCaseReason(String caseAdditionalId) {
		//案由处理
		Example example = new Example(CaseReasonMainRecord.class);
		example.createCriteria().andEqualTo("caseId", caseAdditionalId).andEqualTo("status", "1");
		List<CaseReasonMainRecord> records = caseReasonMainRecordMapper.selectByExample(example);
		if (!ObjectUtils.isEmpty(records)) {
			String reasonName = records.stream().map(reason -> reason.getCaseReasonName()).collect(Collectors.joining(","));
			return reasonName;
		}
		return "";
	}

	/**
	 * 获取上报部门code
	 *
	 * @param caseAdditionalId
	 * @return
	 */
	private String getSourceDeptCode(String caseAdditionalId) {
		//案由处理
		Example example = new Example(CaseReasonMainRecord.class);
		example.createCriteria().andEqualTo("caseId", caseAdditionalId).andEqualTo("status", "1");
		List<CaseReasonMainRecord> records = caseReasonMainRecordMapper.selectByExample(example);
		if (!ObjectUtils.isEmpty(records)) {
			String sourceDeptCode = TERRITORY_CODE_PREFIX + records.get(Constant.INTEGER_0).getTerritoryCode();
			return sourceDeptCode;
		}
		return "";
	}


	/**
	 * 获取areaCode
	 *
	 * @param caseAdditionalRecord
	 * @return
	 */
	private String getAreaCode(CaseAdditionalRecord caseAdditionalRecord) {
		String areaCode = Constant.STRING_HORIZONTAL_BARS;
		String orgCode = caseAdditionalRecord.getOrgCode();
		//优先取member库表中配置的区划编码，如果取不到，截取orgCode
		if (ObjectUtils.isEmpty(caseAdditionalRecord.getOrgCode())) {
			orgCode = Constant.STRING_HORIZONTAL_BARS;
		}
		String gbAreaCode = sysDepartParamService.getGbOrgInfo(orgCode);
		if (!ObjectUtils.isEmpty(gbAreaCode)) {
			areaCode = gbAreaCode.substring(0, 6);
		} else {
			if (orgCode.contains(Constant.STRING_UNDERLINE)) {
				//areaCode = orgCode.substring(0, orgCode.indexOf(Constant.STRING_UNDERLINE));
				areaCode = orgCode.substring(0, 6);
			}
		}
		return areaCode;
	}

	/**
	 * 获取案件类型code
	 *
	 * @param caseType
	 * @return
	 */
	private String getCaseTypeCode(String caseType) {
		String caseTypeCode = Constant.STRING_HORIZONTAL_BARS;
        /*
        系统内部：
        1-简易程序/2-一般程序/3-快速办理
        数据上报规则：
        01-简易程序/02-一般程序
         */
		if (CaseAdditionalTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
			caseTypeCode = "01";
		} else if (CaseAdditionalTypeEnum.NORMAL_PROCEDURE.getCode().equals(caseType)) {
			caseTypeCode = "02";
		} else if (CaseAdditionalTypeEnum.SIMPLE_QUICK.getCode().equals(caseType)) {
			caseTypeCode = "03";
		}
		return caseTypeCode;
	}

	/**
	 * 获取案件来源
	 * 系统内部：
	 * 机构检测报告
	 * 社会举报
	 * 上级行政机关交办
	 * 下级行政机关报请
	 * 有关部门移送
	 * 非现场执法
	 * 巡查中发现
	 * 20221014 同步业务，新增"其他"
	 * 20221019前？ 同步业务，新增"在行政检查中发现"
	 * <p>
	 * 数据上报规则：
	 * 01=在行政检查中发现,
	 * 02=机构检测报告,
	 * 03=社会举报,
	 * 04=上级行政机关交办,
	 * 05=下级行政机构报请,
	 * 06=有关部门移送,
	 * 07=非现场执法
	 * 08=巡查中发现
	 * <p>
	 * 99=其他
	 *
	 * @param caseSource
	 * @return
	 */
	private String getCaseResourceCode(String caseSource) {
		// 2022/3/31 目前系统配置项中无"在行政检查中发现"项，默认这项，有对应值取对应值
		// 2022/9/19 发现系统配置项中新增了"在行政检查中发现"项，需要特殊传入检查编号信息
		String caseSourceCode = "";
		if (CaseSourceEnum.CASE_SOURCE_JGJCBG.getCode().equals(caseSource)) {
			caseSourceCode = "02";
		} else if (CaseSourceEnum.CASE_SOURCE_SHJB.getCode().equals(caseSource)) {
			caseSourceCode = "03";
		} else if (CaseSourceEnum.CASE_SOURCE_SJXZJGJB.getCode().equals(caseSource)) {
			caseSourceCode = "04";
		} else if (CaseSourceEnum.CASE_SOURCE_XJXZJGBQ.getCode().equals(caseSource)) {
			caseSourceCode = "05";
		} else if (CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(caseSource)) {
			caseSourceCode = "06";
		} else if (CaseSourceEnum.CASE_SOURCE_FXCZF.getCode().equals(caseSource)) {
			caseSourceCode = "07";
		} else if (CaseSourceEnum.CASE_SOURCE_XCZFX.getCode().equals(caseSource)) {
			caseSourceCode = "08";
		} else if (CaseSourceEnum.CASE_SOURCE_QT.getCode().equals(caseSource) || "其它".equals(caseSource)) {
			caseSourceCode = "99";
		} else if (CaseSourceEnum.CASE_SOURCE_ZXZJCZFX.getCode().equals(caseSource)) {
			caseSourceCode = "01";
		}
		if (ObjectUtils.isEmpty(caseSourceCode)) {
			throw new BusinessException("未匹配到案件来源信息");
		}
		return caseSourceCode;
	}

	/**
	 * 设置当事人信息
	 * 暂不考虑多当事人分别处罚
	 *
	 * @param baseInfo
	 * @param partInfoVO
	 */
	private void setPartyInfo(JSONObject baseInfo, CasePartiesInfoVo partInfoVO) {
		String partyTypeCode;
		//证件类型
		String certType;
		//证件号码
		String certNumber = partInfoVO.getPartyIdentityCode();
		//联系电话
		String telNumber = partInfoVO.getContactPhone();
		String registerAddress = "";
		String businessAddress = "";

		String partyInfoType = partInfoVO.getPartyType();
		if (PartyTypeEnum.PERSON.getCode().equals(partyInfoType)) {
			partyTypeCode = "01";
			certType = CertTypeDataReportEnum.getReflectCodeByCode(partInfoVO.getPartyIdentityType());
		} else {
			partInfoVO.setPartyIdentityType("统一社会信用代码");
			//单位
			certType = "001";
			String legalCertType = CertTypeDataReportEnum.getReflectCodeByCode(partInfoVO.getPartyIdentityType());
			String entType = partInfoVO.getEntType();
			registerAddress = partInfoVO.getAddress();
			businessAddress = partInfoVO.getAddress();
			//法定代表人证件类型
			baseInfo.put("legalRepresentativeType", legalCertType);
			//法定代表人姓名
			baseInfo.put("legalRepresentative", partInfoVO.getLegalName());
			//法定代表人证件号码
			baseInfo.put("legalRepresentativeIdcard", partInfoVO.getLegalCertNo());

            /*
                项目内枚举：单位类型(1:法人 2:个体工商户 3:其他组织)
                数据上报枚举：01公民/02法人/03其他组织/04个体工商户

                补录存储的类型：1、个人，2、法人，3、个体工商户，4、其他组织

             */
			if (Constant.STRING_3.equals(entType)) {
				partyTypeCode = "04";
			} else if (Constant.STRING_4.equals(entType)) {
				partyTypeCode = "03";
			} else {
				partyTypeCode = "02";
			}
		}
		String partyName = partInfoVO.getPartyName();
		//当事人类型
		baseInfo.put("administrativeCpType", partyTypeCode);
		//当事人名称
		baseInfo.put("administrativeCpName", partyName);
        /*
        当事人证件类型：
        系统内部：
            个人：
                身份证
                。。。
            法人：
                社会统一信用代码
        数据上报规则：
            001	统一社会信用代码
            099	其他法人或其他组织有效证件号码
            111	居民身份证
            112	临时居民身份证
            113	户口簿
            114	中国人民解放军军官证
            115	中国人民武装警察部队警官证
            117	出生医学证明
            118	中国人民解放军士兵证
            119	中国人民武装警察部队士兵证
            120	中国人民解放军文职人员证
            122	中国人民武装警察部队文职人员证
            154	居住证
            411	外交护照
            412	公务护照
            413	公务普通护照
            414	普通护照
            415	旅行证
            511	台湾居民来往大陆通行证港
            516	澳居民来往内地通行证
         */

		//当事人证件类型
		baseInfo.put("administrativeCpCertType", certType);
		//当事人证件号码
		baseInfo.put("administrativeCpCertCode", certNumber);
		//当事人联系电话
		baseInfo.put("administrativeCpTel", telNumber);

          /*map.put("areaCodeLive","");
        map.put("areaNameLive","");
        map.put("addressLive","");
        map.put("areaCodeRegisterd","");
        map.put("areaNameRegisterd","");

        map.put("areaCodeOperating","");
        map.put("areaNameOperating","");
        */
		baseInfo.put("addressRegisterd", registerAddress);
		baseInfo.put("addressOperating", businessAddress);
	}

	/**
	 * 描述： 更新公示时间及地址
	 *
	 * @return
	 * @author: zhengqiang
	 * @date: 2022/7/20
	 * @param: caseId
	 * @param: decisionObj
	 **/
	private void updatePublicDateAndUrl(String caseId, JSONObject decisionObj) {
		CaseDataReportRecord latestReportRecord = caseDataReportRecordService.getLatestReportRecord(caseId, ReportDataTypeEnum.DECISION.getCode());
		if (!ObjectUtils.isEmpty(latestReportRecord)) {
			//获取公示时间
			JSONObject decisionInfo = decisionObj.getJSONObject("decisionInfo");
			LocalDateTime publicDate = (LocalDateTime) decisionInfo.get("publicDate");
			latestReportRecord.setPublicDate(publicDate);
			//拼接url
			String punishDocumentCode = decisionInfo.getString("punishDocumentCode");
			String punishBaseInfoCode = decisionInfo.getString("punishBaseInfoCode");
			try {
				StringBuilder publicUrl = new StringBuilder("https://www.zjzwfw.gov.cn/zjservice/matter/punishment/detail.do?");
				publicUrl.append("unid=").append(URLEncoder.encode(punishDocumentCode, "UTF-8"));
				publicUrl.append("&webid=1");
				publicUrl.append("&guid=").append(punishBaseInfoCode);
				latestReportRecord.setPublicUrl(publicUrl.toString());
			} catch (Exception e) {
				log.error("公示地址拼接异常", e);
			}
			caseDataReportRecordMapper.updateByPrimaryKeySelective(latestReportRecord);
		}
	}
}
